import json
import pandas as pd
import requests as rq
import copy
from coord_convert.transform import wgs2gcj, wgs2bd, gcj2wgs, gcj2bd, bd2wgs, bd2gcj


def main():
    LL = []
    df = pd.read_excel('hubei.xlsx', sheet_name='Sheet1', encoding='utf-8')
    print(df.columns)

    h = {'all':[]}
    # '急诊（心脑血管、外伤等重症）', '血液透析', '恶性肿瘤（含恶性\n血液病）','儿童（含新生儿）', '孕产妇'
    for row in range(0, len(df)):
        if '（' in df.iloc[row, 1].split('\n')[0]:

            name = df.iloc[row, 1].split('\n')[0][:df.iloc[row, 1].split('\n')[0].find('（')]
        else:
            name = df.iloc[row, 1].split('\n')[0]
        h['all'].append({
            'name': name,
            'city': str(df.iloc[row, 0]),
            'categ':[str(df.iloc[row, 3]) != 'nan', str(df.iloc[row, 4]) != 'nan', str(df.iloc[row, 5]) != 'nan',
                     str(df.iloc[row, 6]) != 'nan', str(df.iloc[row, 7]) != 'nan'],
            'tel': str(df.iloc[row, 8]).replace('\n',';').replace(' ',''),
            'spec': str(df.iloc[row, 9]).replace('\n',';')
        })

    for i in range(0, len(h['all'])):
        city = h['all'][i]['city']
        name = h['all'][i]['name']
        url = 'https://restapi.amap.com/v3/place/text?key=de1fb1729e2e4f6fb20d2e6ea3ac8e27' \
            '&keywords=' + name + '&types=090100|090200|090300|090400|090500&city=' + city + '&children=0&offset=1&page=1&extensions=all'
        print(url)
        response = rq.get(url)
        result = response.json()

        if len(result['pois']) != 0:
            for k, v in result['pois'][0].items():
                if v == []:
                    result['pois'][0][k] = ''

            fmt_addr = result['pois'][0]['address']
            fmt_name = result['pois'][0]['name']
            fmt_type1 = result['pois'][0]['type'].split(';')[1]
            fmt_type2 = result['pois'][0]['type'].split(';')[2]
            fmt_alias = result['pois'][0]['alias'].replace('|', '；')
            fmt_district = result['pois'][0]['adname']
            fmt_lng = result['pois'][0]['location'].split(',')[0]
            fmt_lat = result['pois'][0]['location'].split(',')[1]
            fmt_tel = result['pois'][0]['tel']#.replace(';', '；')

            newLon, newLat = gcj2wgs(float(fmt_lng), float(fmt_lat))
            h['all'][i]['lng'] = round(newLon, 6)
            h['all'][i]['lat'] = round(newLat, 6)

            h['all'][i]['name_fmt'] = fmt_name
            h['all'][i]['addr'] = fmt_addr
            h['all'][i]['type1'] = fmt_type1
            h['all'][i]['type2'] = fmt_type2
            h['all'][i]['alias'] = fmt_alias
            h['all'][i]['district'] = fmt_district
            h['all'][i]['tel_gaode'] = fmt_tel
        else:
            h['all'][i]['addr'] = '404'
    with open('hubei1.json','w') as fw:
        fw.write(json.dumps(h, separators=(',',':'), ensure_ascii=False))
if __name__ == '__main__':
    main()